package mylibrary.security;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.commons.codec.binary.Base64;

public class DES {

	public static void main(String[] args) throws Exception {
		
		KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
		keyGenerator.init(56);
		SecretKey secretKey = keyGenerator.generateKey();
		byte[] key_byte = secretKey.getEncoded();		//this is the binary format of key
		System.out.println("key=" + Base64.encodeBase64String(key_byte));
		
		//save the key
		//OutputStream os = new FileOutputStream("d:\\des.key");
		//byte[] key_file = new byte[key_byte.length];
		//os.write(key_file);
		//os.close();
		
		//convert binary key to object
		//DESKeySpec dks = new DESKeySpec(key_byte);
		//SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		//SecretKey key = keyFactory.generateSecret(dks);		//get the key
		
		
		Cipher cipher = Cipher.getInstance("DES");
		cipher.init(Cipher.ENCRYPT_MODE, secretKey);
		System.out.println("Original data=" + Base64.encodeBase64String("Hello".getBytes()));
		byte[] encryptedData = cipher.doFinal("Hello".getBytes());
		System.out.println("After encryption=" + Base64.encodeBase64String(encryptedData));
	}
}
